<?php
namespace app\controller;

use support\Request;
use support\Db;

class BudgetController
{
    /**
     * 验证用户是否有权限操作该账本
     */
    private function checkBookPermission($bookId, $userId)
    {
        return Db::table('account_book_users')
            ->where('book_id', $bookId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->exists();
    }

    /**
     * 设置预算
     */
    public function setBudget(Request $request)
    {
        try {
            $data = [
                'book_id' => $request->post('book_id'),
                'category_id' => $request->post('category_id'),
                'period_type' => $request->post('period_type'), // 1按月 2按年
                'amount' => $request->post('amount'),
            ];

            // 验证必填字段
            if (empty($data['book_id']) || empty($data['category_id']) || 
                empty($data['period_type']) || empty($data['amount'])) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($data['book_id'], $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 验证分类是否属于该账本且为支出类型
            $category = Db::table('categories')
                ->where('id', $data['category_id'])
                ->where('book_id', $data['book_id'])
                ->where('type', 1) // 支出类型
                ->where('status', 1)
                ->first();

            if (!$category) {
                return json([
                    'code' => 400,
                    'msg' => '分类不存在或不是支出类型'
                ]);
            }

            // 计算月度和年度金额
            if ($data['period_type'] == 1) { // 按月
                $data['monthly_amount'] = $data['amount'];
                $data['yearly_amount'] = $data['amount'] * 12;
            } else { // 按年
                $data['yearly_amount'] = $data['amount'];
                $data['monthly_amount'] = $data['amount'] / 12;
            }

            // 更新或插入预算
            Db::table('budgets')
                ->updateOrInsert(
                    [
                        'book_id' => $data['book_id'],
                        'category_id' => $data['category_id']
                    ],
                    [
                        'period_type' => $data['period_type'],
                        'amount' => $data['amount'],
                        'monthly_amount' => $data['monthly_amount'],
                        'yearly_amount' => $data['yearly_amount'],
                        'status' => 1,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]
                );

            return json([
                'code' => 0,
                'msg' => '设置成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取预算使用情况
     */
    public function getBudgetUsage(Request $request)
    {
        try {
            $bookId = $request->get('book_id');
            $year = $request->get('year');
            $month = $request->get('month');

            if (empty($bookId) || empty($year)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($bookId, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 获取预算数据
            $budgets = Db::table('budgets as b')
                ->join('categories as c', 'b.category_id', '=', 'c.id')
                ->where('b.book_id', $bookId)
                ->where('b.status', 1)
                ->select([
                    'b.*',
                    'c.name as category_name',
                    'c.color as category_color'
                ])
                ->get();

            // 获取实际支出数据
            $query = Db::table('transactions')
                ->where('book_id', $bookId)
                ->where('type', 1) // 支出
                ->where('status', 1)
                ->where('trans_date', 'like', $year . '%');

            // 如果指定了月份，则只统计该月数据
            if (!empty($month)) {
                $query->where('trans_date', 'like', $year . '-' . $month . '%');
            }

            $expenses = $query->selectRaw('category_id, SUM(amount) as total_amount')
                ->groupBy('category_id')
                ->get()
                ->keyBy('category_id');

            // 合并预算和实际支出数据
            foreach ($budgets as &$budget) {
                // 根据查询期间确定预算基准金额
                $budgetAmount = empty($month) ? $budget->yearly_amount : $budget->monthly_amount;
                
                $usedAmount = $expenses[$budget->category_id]->total_amount ?? 0;
                $budget->budget_amount = $budgetAmount;
                $budget->used_amount = $usedAmount;
                $budget->remaining_amount = $budgetAmount - $usedAmount;
                $budget->usage_rate = $budgetAmount > 0 
                    ? round(($usedAmount / $budgetAmount) * 100, 2) 
                    : 0;
            }

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $budgets
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取预算列表
     */
    public function list(Request $request)
    {
        try {
            $bookId = $request->get('book_id');
            $periodType = $request->get('period_type');
            $periodValue = $request->get('period_value');

            if (empty($bookId) || empty($periodType) || empty($periodValue)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($bookId, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 获取预算数据
            $budgets = Db::table('budgets as b')
                ->join('categories as c', 'b.category_id', '=', 'c.id')
                ->where('b.book_id', $bookId)
                ->where('b.period_type', $periodType)
                ->where('b.period_value', $periodValue)
                ->where('b.status', 1)
                ->select([
                    'b.*',
                    'c.name as category_name',
                    'c.color as category_color'
                ])
                ->get();

            // 获取实际支出数据
            $startDate = $periodType == 1 
                ? $periodValue . '-01' 
                : $periodValue . '-01-01';
            
            $endDate = $periodType == 1 
                ? date('Y-m-t', strtotime($startDate))
                : $periodValue . '-12-31';

            $expenses = Db::table('transactions')
                ->where('book_id', $bookId)
                ->where('type', 1) // 支出
                ->where('status', 1)
                ->whereBetween('trans_date', [$startDate, $endDate])
                ->selectRaw('category_id, SUM(amount) as total_amount')
                ->groupBy('category_id')
                ->get()
                ->keyBy('category_id');

            // 合并预算和实际支出数据
            foreach ($budgets as &$budget) {
                $budget->used_amount = $expenses[$budget->category_id]->total_amount ?? 0;
                $budget->remaining_amount = $budget->amount - $budget->used_amount;
                $budget->usage_rate = $budget->amount > 0 
                    ? round(($budget->used_amount / $budget->amount) * 100, 2) 
                    : 0;
            }

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $budgets
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除预算
     */
    public function delete(Request $request)
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取预算信息
            $budget = Db::table('budgets')
                ->where('id', $id)
                ->where('status', 1)
                ->first();

            if (!$budget) {
                return json([
                    'code' => 404,
                    'msg' => '预算不存在'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($budget->book_id, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 软删除
            Db::table('budgets')
                ->where('id', $id)
                ->update([
                    'status' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return json([
                'code' => 0,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 